package com.lg.wechat.business.oauth.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.lg.utils.RedisTemplateUtil;
import com.lg.wechat.business.oauth.service.WxOauthService;
import com.lg.wechat.business.wxuser.entity.WxUser;
import com.lg.wechat.common.annotation.Clear;
import com.lg.wechat.utils.Constant;
import com.lg.wechat.utils.CookieUtil;
import me.chanjar.weixin.common.exception.WxErrorException;

/**
 * <pre>
 *  注意：此contorller 实现WxMpMenuService接口，仅是为了演示如何调用所有菜单相关操作接口，
 *      实际项目中无需这样，根据自己需要添加对应接口即可
 * </pre>
 */
@RestController
@RequestMapping("/wx/oauth")
@Clear
public class WxOauthController  {

  
  @Autowired
  WxOauthService wxOauthService;
  
  @Autowired
  RedisTemplate<String, Object> redisTemplate;
  
  @RequestMapping("/index")
  @Clear
  public void index(HttpServletRequest request,HttpServletResponse response,String code,String state) throws WxErrorException, IOException{
	  WxUser wxUser= wxOauthService.oauthSave(code);
	  if(wxUser!=null){
	        CookieUtil.addCookie(response, Constant.Token,wxUser.getOpenId(),Constant.cookieMaxAge);
	        RedisTemplateUtil.set(wxUser.getOpenId(), wxUser, Constant.cookieMaxAge);
	        response.sendRedirect(state);
	  }else{
		    response.sendRedirect(state);
	  }
  }
  
	@GetMapping("/test")
	public ModelAndView test(){
		ModelAndView mView=new ModelAndView("wechat/index");
		return mView;
	}
}
